import { useState, useEffect } from 'react';
import { Table, Button, Pagination, Image, message } from 'antd';
import { PictureOutlined } from '@ant-design/icons';
import { goodsList, delGoods } from '@/api/account';
import dayjs from 'dayjs';
import { serverUrl } from '@/utils/common';

const GoodsList = () => {
  const [tableData, setTableData] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10
  });

  // 获取商品列表
  const fetchGoodsList = async () => {
    try {
      setLoading(true);
      const res = await goodsList({
        currentPage: pagination.current,
        pageSize: pagination.pageSize
      });
      setTableData(res.data || []);
      setTotal(res.total || 0);
    } catch (error) {
      message.error('获取商品列表失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchGoodsList();
  }, [pagination.current, pagination.pageSize]);

  // 处理分页变化
  const handleTableChange = (pagination) => {
    setPagination(pagination);
  };

  // 格式化时间
  const formatTime = (text) => {
    return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
  };

  // 删除商品
  const handleDelete = async (id) => {
    try {
      const res = await delGoods({ id });
      if (res.code === 0) {
        message.success('删除成功');
        fetchGoodsList();
      } else {
        message.error(res.msg || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
      console.error(error);
    }
  };

  // 编辑商品
  const handleEdit = (record) => {
    console.log('编辑商品:', record);
    // 这里可以跳转到编辑页面或打开编辑弹窗
  };

  // 表格列配置
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '商品分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price}`
    },
    {
      title: '商品图片',
      key: 'imgUrl',
      width: 80,
      render: (_, record) => (
        record.imgUrl ? (
          <Image 
            src={`${serverUrl}${record.imgUrl}`} 
            height={40}
            preview={false}
            style={{ objectFit: 'contain' }}
          />
        ) : (
          <PictureOutlined style={{ fontSize: '20px', color: '#ccc' }} />
        )
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'ctime',
      key: 'ctime',
      render: (text) => formatTime(text),
    },
    {
      title: '评价',
      dataIndex: 'rating',
      key: 'rating',
    },
    {
      title: '销量',
      dataIndex: 'sellCount',
      key: 'sellCount',
    },
    {
      title: '商品描述',
      dataIndex: 'goodsDesc',
      key: 'goodsDesc',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <div style={{ display: 'flex', gap: '8px' }}>
          <Button 
            type="primary" 
            size="small" 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="primary" 
            danger 
            size="small" 
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div>
      <Table
        columns={columns}
        dataSource={tableData}
        rowKey="id"
        loading={loading}
        pagination={{
          ...pagination,
          total,
          pageSizeOptions: ['5', '10', '20', '30'],
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
        onChange={handleTableChange}
        scroll={{ x: true }}
      />
    </div>
  );
};

export default GoodsList;